package org.stephen.recommend.util;

import java.io.*;

/**
 * ClassName: SerializeUtil
 * Description:
 * Date: 2020/12/16 15:30
 *
 * @author stephen.qiu
 */
public class SerializeUtils {
    /**
     * 对象序列化为字符串
     *
     * @param object
     * @return
     */
    public static String serializeObject(Object object) {
        String objectStr = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
            out.writeObject(object);
            //必须是ISO-8859-1
            objectStr = byteArrayOutputStream.toString("ISO-8859-1");
            out.close();
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return objectStr;
    }

    /**
     * 字符串序列化为对象
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static Object stringSerializeObject(String str) {
        if (str == null) {
            return null;
        }
        Object object = null;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            object = objectInputStream.readObject();
            objectInputStream.close();
            byteArrayInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;
    }
}
